package com.cskaoyan.market.admin.service.impl;

import com.cskaoyan.market.admin.service.MarketGoodsService;
import com.cskaoyan.market.admin.vo.BrandVo;
import com.cskaoyan.market.admin.vo.CategoryVo;
import com.cskaoyan.market.admin.vo.DetailGoodsVo;
import com.cskaoyan.market.db.domain.*;
import com.cskaoyan.market.db.mapper.*;
import com.cskaoyan.market.util.MarketConstant;
import com.cskaoyan.market.util.MyBatisUtil;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.SqlSession;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author James
 * @since 2023/03/20 22:37
 */

public class MarketGoodsServiceImpl implements MarketGoodsService {


    @Override
    public Map<String, Object> catAndBrand() {

        SqlSession session = MyBatisUtil.getSession();
        MarketCategoryMapper categoryMapper = session.getMapper(MarketCategoryMapper.class);
        //创建一个example对象
        MarketCategoryExample categoryExample = new MarketCategoryExample();
        categoryExample.or().andDeletedEqualTo(false);
        List<MarketCategory> marketCategories = categoryMapper.selectByExample(categoryExample);

        MarketBrandMapper brandMapper = session.getMapper(MarketBrandMapper.class);
        MarketBrandExample marketBrandExample = new MarketBrandExample();
        marketBrandExample.or().andDeletedEqualTo(false);
        List<MarketBrand> marketBrands = brandMapper.selectByExample(marketBrandExample);
        //关闭
        session.commit();
        session.close();

        Map<Integer, List<MarketCategory>> listMap = groupByPid(marketCategories);
        List<MarketCategory> l1Categories = listMap.get(MarketConstant.MARKET_CATEGORY_LEVEL_1);
        ArrayList<Object> l1vos = new ArrayList<>();
        for (MarketCategory l1Category : l1Categories) {
            //每个一级分类
            CategoryVo l1VO = new CategoryVo();
            l1VO.setLabel(l1Category.getName());
            l1VO.setValue(l1Category.getId());
            List<CategoryVo> l2vos = new ArrayList<>();
            List<MarketCategory> l2CategoriesOfL1 = listMap.get(l1Category.getId());
            for (MarketCategory l2 : l2CategoriesOfL1) {
                CategoryVo l2Vo = new CategoryVo();
                l2Vo.setValue(l2.getId());
                l2Vo.setLabel(l2.getName());
                l2vos.add(l2Vo);
            }
            l1VO.setChildren(l2vos);
            l1vos.add(l1VO);
        }
        //处理品牌
        List<BrandVo> brandVos = new ArrayList<>();
        for (MarketBrand marketBrand : marketBrands) {
            BrandVo brandVo = new BrandVo();
            brandVo.setValue(marketBrand.getId());
            brandVo.setLabel(marketBrand.getName());
            brandVos.add(brandVo);
        }

        Map<String, Object> result = new HashMap<>();
        result.put("categoryList", l1vos);
        result.put("brandList", brandVos);
        return result;

    }

    /**
     * 将list按照pid来进行分类，放入map中
     * 再利用map.get(pid=0)可以获取到一级分类
     * 在此基础上，我们再用map.get(一级分类的编号)便可以获取到对应的二级分类
     *
     * @param marketCategories
     * @return
     */
    private Map<Integer, List<MarketCategory>> groupByPid(List<MarketCategory> marketCategories) {
        Map<Integer, List<MarketCategory>> categoriesGroupByPid = new HashMap<>();
        for (MarketCategory category : marketCategories) {
            Integer pid = category.getPid();
            List<MarketCategory> list = categoriesGroupByPid.get(pid);
            if (list == null) {
                list = new ArrayList<>();
                categoriesGroupByPid.put(pid, list);
            }
            list.add(category);
        }
        return categoriesGroupByPid;
    }

    @Override
    public List<MarketGoods> list(int page, int limit, String goodsSn, String name, String sort, String order, String goodsId) {
        SqlSession session = MyBatisUtil.getSession();
        MarketGoodsMapper mapper = session.getMapper(MarketGoodsMapper.class);
        MarketGoodsExample marketGoodsExample = new MarketGoodsExample();
        PageHelper.startPage(page, limit);
        MarketGoodsExample.Criteria criteria = marketGoodsExample.createCriteria();
        criteria.andDeletedEqualTo(false);
        if (!StringUtils.isEmpty(goodsSn)) {
            criteria.andGoodsSnEqualTo(goodsSn);
        }
        if (!StringUtils.isEmpty(name)) {
            criteria.andNameLike("%" + name + "%");
        }
        if (!StringUtils.isEmpty(goodsId)) {
            criteria.andIdEqualTo(Integer.parseInt(goodsId));
        }
        marketGoodsExample.setOrderByClause(sort + " " + order);
        List<MarketGoods> marketGoods = mapper.selectByExample(marketGoodsExample);
        session.commit();
        session.close();
        return marketGoods;
    }


    @Override
    public DetailGoodsVo detail(String id) {
        SqlSession session = MyBatisUtil.getSession();
        MarketGoodsMapper mapper = session.getMapper(MarketGoodsMapper.class);
        MarketGoods marketGoods = mapper.selectByPrimaryKey(Integer.parseInt(id));
        DetailGoodsVo detailGoodsVo = new DetailGoodsVo();
        detailGoodsVo.setGoods(marketGoods);

        MarketGoodsAttributeMapper mapper1 = session.getMapper(MarketGoodsAttributeMapper.class);
        MarketGoodsAttributeExample marketGoodsAttributeExample = new MarketGoodsAttributeExample();
        marketGoodsAttributeExample.createCriteria().andGoodsIdEqualTo(marketGoods.getId());
        List<MarketGoodsAttribute> marketGoodsAttributes = mapper1.selectByExample(marketGoodsAttributeExample);
        MarketGoodsAttribute[] marketGoodsAttributes1 = new MarketGoodsAttribute[marketGoodsAttributes.size()];
        MarketGoodsAttribute[] marketGoodsAttributes2 = marketGoodsAttributes.toArray(marketGoodsAttributes1);
        detailGoodsVo.setAttributes(marketGoodsAttributes2);

        Integer categoryId = marketGoods.getCategoryId();
        MarketCategoryMapper mapper2 = session.getMapper(MarketCategoryMapper.class);
        MarketCategory marketCategory = mapper2.selectByPrimaryKey(categoryId);
        Integer pid = marketCategory.getPid();

        Integer[] ints = {categoryId, pid};
        detailGoodsVo.setCategoryIds(ints);

        MarketGoodsProductMapper mapper3 = session.getMapper(MarketGoodsProductMapper.class);
        MarketGoodsProductExample marketGoodsProductExample = new MarketGoodsProductExample();
        marketGoodsProductExample.createCriteria().andGoodsIdEqualTo(marketGoods.getId());
        List<MarketGoodsProduct> marketGoodsProducts = mapper3.selectByExample(marketGoodsProductExample);
        MarketGoodsProduct[] marketGoodsProducts1 = new MarketGoodsProduct[marketGoodsProducts.size()];
        MarketGoodsProduct[] marketGoodsProducts2 = marketGoodsProducts.toArray(marketGoodsProducts1);
        detailGoodsVo.setProducts(marketGoodsProducts2);

        MarketGoodsSpecificationMapper mapper4 = session.getMapper(MarketGoodsSpecificationMapper.class);
        MarketGoodsSpecificationExample marketGoodsSpecificationExample = new MarketGoodsSpecificationExample();
        marketGoodsSpecificationExample.createCriteria().andGoodsIdEqualTo(marketGoods.getId());
        List<MarketGoodsSpecification> marketGoodsSpecifications = mapper4.selectByExample(marketGoodsSpecificationExample);
        MarketGoodsSpecification[] marketGoodsSpecifications1 = new MarketGoodsSpecification[marketGoodsSpecifications.size()];
        MarketGoodsSpecification[] marketGoodsSpecifications2 = marketGoodsSpecifications.toArray(marketGoodsSpecifications1);
        detailGoodsVo.setSpecifications(marketGoodsSpecifications2);
        session.commit();
        session.close();
        return detailGoodsVo;


    }

    @Override
    public void delete(String id) {
        SqlSession session = MyBatisUtil.getSession();
        MarketGoodsMapper mapper = session.getMapper(MarketGoodsMapper.class);
        MarketGoodsExample marketGoodsExample = new MarketGoodsExample();
        marketGoodsExample.createCriteria().andIdEqualTo(Integer.parseInt(id));
        MarketGoods marketGoods = mapper.selectOneByExample((marketGoodsExample));
        marketGoods.setDeleted(true);
        marketGoods.setUpdateTime(LocalDateTime.now());
        mapper.updateByPrimaryKey(marketGoods);

        session.commit();
        session.close();
    }

    @Override
    public void update(MarketGoodsAttribute[] attributes, MarketGoods goods, MarketGoodsProduct[] products, MarketGoodsSpecification[] specifications) {
        BigDecimal retailPrice = new BigDecimal(Integer.MAX_VALUE);
        for (MarketGoodsProduct product : products) {
            if (retailPrice.compareTo(product.getPrice()) == 1) {
                retailPrice = product.getPrice();
            }
        }
        // for (MarketGoods good : goods) {
        //     good.setRetailPrice(retailPrice);
        //     good.setAddTime(LocalDateTime.now());
        //     good.setDeleted(false);
        // }
        SqlSession session = MyBatisUtil.getSession();
        MarketGoodsMapper goodsMappermapper = session.getMapper(MarketGoodsMapper.class);
        MarketGoodsAttributeMapper attributeMapper = session.getMapper(MarketGoodsAttributeMapper.class);
        MarketGoodsProductMapper productMapper = session.getMapper(MarketGoodsProductMapper.class);
        MarketGoodsSpecificationMapper specificationMapper = session.getMapper(MarketGoodsSpecificationMapper.class);


        Integer id = goods.getId();

        for (MarketGoodsAttribute attribute : attributes) {
            attribute.setGoodsId(id);
            attribute.setUpdateTime(LocalDateTime.now());
            attribute.setDeleted(false);
            attributeMapper.updateByPrimaryKey(attribute);
        }
        for (MarketGoodsProduct product : products) {
            product.setGoodsId(id);
            product.setUpdateTime(LocalDateTime.now());
            product.setDeleted(false);
            productMapper.updateByPrimaryKey(product);
        }

        for (MarketGoodsSpecification specification : specifications) {
            specification.setGoodsId(id);
            specification.setUpdateTime(LocalDateTime.now());
            specification.setDeleted(false);
            specificationMapper.updateByPrimaryKey(specification);
        }
        goods.setRetailPrice(retailPrice);
        goods.setAddTime(LocalDateTime.now());
        goods.setDeleted(false);
        goodsMappermapper.updateByPrimaryKey(goods);

        session.commit();
        session.close();

    }
}
